import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElRow,
  ElCol,
  ElMessage,
  ElIcon
} from 'element-plus'
import { Plus, CirclePlus, CircleClose } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

import type { lampModel } from '~/store/monitor/typings'
import BaseUpload from '~/components/ProForm/BaseUpload'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../../index.module.scss'

import type { InfoValuesType, loopListType } from './typings'
export default defineComponent({
  emits: ['submitForm'],
  setup(props, { emit, expose }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<InfoValuesType>({})
    const state = reactive({
      visible: false,
      type: '',
      id: ''
    })
    const openAdd = (row?: any) => {
      state.visible = true
      if (row) {
        initData(row.id)
        state.type = 'edit'
        state.id = row.id
      } else {
        ruleForm.monitorLampLoopVOList = [{}]
      }
    }
    const initData = async (id: string) => {
      const { code, data } = await store.dispatch('singleLamp/DeviceView', { id })
      if (code === 200) {
        ruleForm.name = data.name
        ruleForm.code = data.code
        ruleForm.simCardNo = data.simCardNo
        ruleForm.deliverDate = data.deliverDate
        ruleForm.modelId = data.modelId
        ruleForm.deviceUrlArr = data?.deviceUrl ? data?.deviceUrl?.split?.(',') : []
        ruleForm.simUrlArr = data?.simUrl ? data?.simUrl?.split?.(',') : []
        ruleForm.monitorLampLoopVOList = data.monitorLampLoopVOList.length
          ? data.monitorLampLoopVOList.map((item: loopListType) => {
              return {
                num: item.num,
                position: item.position,
                power: item.power
              }
            })
          : [{}]
      }
    }

    const singleLampState = useVuexGetters('singleLamp', [
      'communicationStateOpt',
      'communicationStateEnum',
      'runStatus',
      'devBrand',
      'devModel',
      'positionStateOpt',
      'positionStateNum'
    ])

    const rules = reactive<FormRules>({
      name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
      code: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
      modelId: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }]
    })
    const addLoop = () => {
      ruleForm.monitorLampLoopVOList?.push({})
    }
    const delLoop = (index: number) => {
      ruleForm.monitorLampLoopVOList?.splice(index, 1)
    }
    //  提交
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const params = { ...ruleForm }
          params.name = handleTrim(params.name!)
          params.deviceUrl = params.deviceUrlArr?.length ? params.deviceUrlArr.join(',') : ''
          params.simUrl = params.simUrlArr?.length ? params.simUrlArr.join(',') : ''
          delete params.deviceUrlArr
          delete params.simUrlArr
          if (state.type === 'edit') params.id = state.id
          const { code } = await store.dispatch(
            state.type === 'edit' ? 'singleLamp/DeviceUpdate' : 'singleLamp/DeviceAdd',
            params
          )
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            emit('submitForm')
            resetForm()
          }
        }
      })
    }
    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (ruleForm.deviceUrlArr as string[])?.push(link)
      }
    }
    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.response?.data?.link || file?.url
      if (link) {
        ruleForm.deviceUrlArr = (ruleForm.deviceUrlArr as string[])?.filter((item) => item !== link)
      }
    }
    // 上传成功回调sim卡
    const handleUploadSuccessSim = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (ruleForm.simUrlArr as string[])?.push(link)
      }
    }
    // 移除对应的文件sim卡
    const handleRemoveUploadFileSim = (file: Record<string, any>) => {
      const link = file?.response?.data?.link || file?.url
      if (link) {
        ruleForm.simUrlArr = (ruleForm.simUrlArr as string[])?.filter((item) => item !== link)
      }
    }

    const resetForm = () => {
      ruleFormRef.value?.resetFields()
      state.visible = false
    }
    expose({ openAdd })
    onMounted(() => {})

    return () => (
      <ElDialog
        title={state.type === 'edit' ? '编辑单灯控制器' : '新增单灯控制器'}
        modelValue={state.visible}
        beforeClose={resetForm}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={900}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm
          ref={ruleFormRef}
          model={ruleForm}
          rules={rules}
          label-width="100px"
          labelPosition="right"
        >
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem label="设备名称" prop="name">
                <ElInput v-model={ruleForm.name} placeholder="请输入设备名称"></ElInput>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem label="设备编号" prop="code">
                <ElInput v-model={ruleForm.code} placeholder="请输入设备编号"></ElInput>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem label="sim卡号" prop="simCardNo">
                <ElInput v-model={ruleForm.simCardNo} placeholder="请输入SIM卡号"></ElInput>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem label="设备型号" prop="modelId">
                <ElSelect v-model={ruleForm.modelId} clearable placeholder="请选择设备型号">
                  {singleLampState.devModel?.value?.map((item: lampModel) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id} />
                  ))}
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem label="投运日期" prop="deliverDate">
                <ElDatePicker
                  v-model={ruleForm.deliverDate}
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  type="date"
                  clearable={false}
                  placeholder="请选择投运日期"
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={16}>
              <ElFormItem label="设备图" prop="deviceUrlArr">
                <BaseUpload
                  listType="picture-card"
                  fileList={(ruleForm.deviceUrlArr as string[])?.map?.((item) => ({
                    name: '图片',
                    url: item,
                    response: {
                      data: {
                        link: item
                      }
                    }
                  }))}
                  accept=".jpg,.png"
                  limit={4}
                  onSuccess={handleUploadSuccess}
                  onRemove={handleRemoveUploadFile}
                >
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                </BaseUpload>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={16}>
              <ElFormItem label="SIM卡图" prop="simUrlArr">
                <BaseUpload
                  listType="picture-card"
                  fileList={(ruleForm.simUrlArr as string[])?.map?.((item) => ({
                    name: '图片',
                    url: item,
                    response: {
                      data: {
                        link: item
                      }
                    }
                  }))}
                  accept=".jpg,.png"
                  limit={4}
                  onSuccess={handleUploadSuccessSim}
                  onRemove={handleRemoveUploadFileSim}
                >
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                </BaseUpload>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={20}>
              <ElFormItem label="单灯回路">
                {ruleForm.monitorLampLoopVOList?.map((item: loopListType, index) => (
                  <div style="display:flex">
                    <ElFormItem labelWidth={0}>
                      <ElInput
                        v-model={item.num}
                        placeholder="回路"
                        type="number"
                        class={styles.loopWrapper}
                      ></ElInput>
                    </ElFormItem>
                    <ElFormItem labelWidth={0}>
                      <ElSelect
                        v-model={item.position}
                        clearable
                        placeholder="请选择方位"
                        valueKey="key"
                        class={styles.loopWrapper}
                      >
                        <ElOption key="0" label="主道" value="0" />
                        <ElOption key="1" label="辅道" value="1" />
                      </ElSelect>
                    </ElFormItem>
                    <ElFormItem labelWidth={0}>
                      <ElInput
                        v-model={item.power}
                        placeholder="功率"
                        class={styles.loopWrapper}
                      ></ElInput>
                      W
                    </ElFormItem>
                    {ruleForm.monitorLampLoopVOList?.length! < 6 && (
                      <div onClick={addLoop} style="margin:4px 12px 0 8px">
                        <ElIcon size={20} color="red">
                          <CirclePlus />
                        </ElIcon>
                      </div>
                    )}
                    {ruleForm.monitorLampLoopVOList?.length! > 1 && (
                      <div onClick={() => delLoop(index)}>
                        <ElIcon size={20} style="margin-top:4px">
                          <CircleClose />
                        </ElIcon>
                      </div>
                    )}
                  </div>
                ))}
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </ElDialog>
    )
  }
})
